package com.yjd.comm.base.control;

import com.yjd.comm.base.model.Model;
import com.yjd.comm.base.model.ResultModel;
import com.yjd.comm.system.dto.AdminDataWrap;
import com.yjd.comm.system.dto.OperParamDto;
import com.yjd.comm.system.util.AdminDataUtil;
import com.yjd.comm.user.dto.UserSession;
import com.yjd.comm.user.enums.ClientChannelEnum;
import com.yjd.comm.user.util.UserUtil;
import com.yjd.comm.util.FrameUtil;
import com.yjd.comm.util.ServletUtil;
import com.yjd.comm.util.StringUtil;
import com.yjd.comm.vo.Constant.ResultEnum;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Map;

public abstract class BaseControl {

    protected Logger logger = Logger.getLogger(this.getClass());

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    public static final String RESULT_PAGE = "/exception/operateException";

    /**
     * 将request中的数据绑定到当前control对应的model中
     *
     * @param request
     * @return
     */
    public <T extends Model> T getModelByRequest(HttpServletRequest request) {
        return ServletUtil.bindRequestToModel(request, getModelType());
    }

    /**
     * 获取当前control对应的model的类型
     *
     * @return
     */
    protected Class<?> getModelType() {
        return null;
    }

    /**
     * @param key
     * @return Object
     * @Title: getSessionCachedValue
     * @Description: 获取session中的值
     */
    public Object getSessionCached(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        return ServletUtil.getSessionAttribute(request, response, key);
    }

    /**
     * @param key
     * @param value
     * @return void
     * @Title: setSessionCached
     * @Description: 向session中放入对象
     */
    public void setSessionCached(String key, Object value) {
        if (StringUtils.isBlank(key)) {
            return;
        }
        ServletUtil.putSession(request, response, key, value);
    }

    /**
     * @param request
     * @param response
     * @Title: setReqAndResp
     * @Description: 初始化ServletAPI
     */
    @ModelAttribute
    public void setReqAndResp(HttpServletRequest request,
                              HttpServletResponse response) {
        this.request = request;
        this.response = response;

        AdminDataWrap loginAdmin = AdminDataUtil.getAdminDataWrap(this.request, this.response);
        if(null != loginAdmin){
            this.request.setAttribute("sign", DigestUtils.md5Hex(loginAdmin.getAdminModel().getPassword() + loginAdmin.getAdminModel().getAdmin_id()));
            this.request.setAttribute("uid", loginAdmin.getAdminModel().getAdmin_id());
        }
    }

    /**
     * 向客户端输出成功信息
     *
     * @param msg
     * @throws Exception
     */
    public void successMsg(String msg) throws Exception {
        ServletUtil.outputJsonMessage(request, response, new ResultModel(
                ResultEnum.SUCCESS, null, msg, null).toMap());
    }

    /**
     * 向客户端输出成功信息
     *
     * @param referer
     *            回调url，可以为空
     * @param msgKey
     *            消息在default.properties文件中的key
     * @param msgKeyparam
     *            msgKey中的占位符替换对象
     * @throws Exception
     */
    public void successMsg(String referer, String msgKey, Object... msgKeyparam)
            throws Exception {
        this.msg(ResultEnum.SUCCESS, null, referer,
                FrameUtil.getResource(msgKey, msgKeyparam));
    }

    /**
     * 向客户端输出失败信息
     *
     * @param msg
     * @throws Exception
     */
    public void errorMsg(String msg) throws Exception {
        ServletUtil.outputJsonMessage(request, response, new ResultModel(
                ResultEnum.ERROR, null, msg, null).toMap());
    }

    /**
     * 输出数据
     *
     * @param data
     * @throws Exception
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void successData(Map data) throws Exception {
        ResultModel rm = new ResultModel(ResultEnum.SUCCESS, null, null, null);
        rm.setData(data);
        ServletUtil.outputJsonMessage(request, response, rm.toMap());
    }

    /**
     * 输出数据
     *
     * @param data
     * @throws Exception
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public void successData(String msg, Map data) throws Exception {
        ResultModel rm = new ResultModel(ResultEnum.SUCCESS, null, msg, null);
        rm.setData(data);
        ServletUtil.outputJsonMessage(request, response, rm.toMap());
    }

    /**
     * 跳转到正确结果页面
     *
     * @param referer
     *            回调url，可以为空
     * @param msgKey
     *            消息在default.properties文件中的key
     * @param msgKeyparam
     *            msgKey中的占位符替换对象
     * @return
     */
    public String toSuccessPage(String referer, String msgKey,
                                Object... msgKeyparam) {
        ResultModel resultModel = new ResultModel(ResultEnum.SUCCESS, null,
                FrameUtil.getResource(msgKey, msgKeyparam), referer);
        request.setAttribute("result", resultModel.toMap());
        return RESULT_PAGE;
    }

    /**
     * 向客户端输出错误信息
     *
     * @param referer     回调url，可以为空
     * @param msgKey      消息在default.properties文件中的key
     * @param msgKeyparam msgKey中的占位符替换对象
     * @throws Exception
     */
    public void errorMsg(String referer, String msgKey, Object... msgKeyparam)
            throws Exception {
        this.msg(ResultEnum.ERROR, null, referer, msgKey, msgKeyparam);
    }

    /**
     * 跳转到错误结果页面
     *
     * @param referer
     *            回调url，可以为空
     * @param msgKey
     *            消息在default.properties文件中的key
     * @param msgKeyparam
     *            msgKey中的占位符替换对象
     * @return
     */
    public String toErrorPage(String referer, String msgKey,
                              Object... msgKeyparam) {
//		ResultModel resultModel = new ResultModel(ResultEnum.ERROR, null,
//				FrameUtil.getResource(msgKey, msgKeyparam), referer);
//		request.setAttribute("result", resultModel.toMap());
//		return RESULT_PAGE;
        return toErrorPageMoreTime(referer,msgKey,2,msgKeyparam);
    }

    /**
     *
     * @param referer  回调url，可以为空
     * @param msgKey  回调url，可以为空
     * @param time 指定页面停留的秒数
     * @param msgKeyparam
     * @return
     */
    public String toErrorPageMoreTime(String referer, String msgKey,int time,
                                      Object... msgKeyparam) {
        ResultModel resultModel = new ResultModel(ResultEnum.ERROR, null,
                FrameUtil.getResource(msgKey, msgKeyparam), referer);
        request.setAttribute("result", resultModel.toMap());
        request.setAttribute("waitSeconds",time);
        return RESULT_PAGE;
    }

    /**
     * 向客户端输出信息
     *
     * @param resultEnum
     * @param code
     * @param referer
     * @param msgKey
     * @param msgKeyparam
     * @throws Exception
     */
    private void msg(ResultEnum resultEnum, String code, String referer,
                    String msgKey, Object... msgKeyparam) throws Exception {
        ServletUtil.outputJsonMessage(request, response, new ResultModel(
                resultEnum, code, FrameUtil.getResource(msgKey, msgKeyparam),
                referer).toMap());
    }

    public String getParameter(String key) throws UnsupportedEncodingException {
        String pram = "";
        if (StringUtil.isNotEmpty(request.getParameter(key)))
            pram = new String(request.getParameter(key).getBytes("ISO-8859-1"),
                    "utf-8");
        return pram;
    }

    /**
     * 获取登陆用户信息
     *
     * @return
     */
    protected UserSession getUserSession() {
        return UserUtil.getUserModel(request, response, ClientChannelEnum.PIC);
    }


    /**
     * 获取用户id
     *
     * @return
     */
    protected Long getSessionUserId() {
        UserSession u = getUserSession();
        return u != null ? u.getUser_id().longValue() : null;
    }

    /**
     * 获取操作信息
     *
     * @return
     */
    public OperParamDto getOperParamDto() {
        return AdminDataUtil.getOperParamDto(request, response);
    }
}
